import router from "./router";
import { userStore } from "./store/user";
import {collapseStore} from "./store/collapse";
//定义白名单，不需要验证
const whiteList = ['/login']
router.beforeEach(async (to,from,next) =>{
    const ustore = userStore();
    const mstore = collapseStore();
    console.log(to)
    console.log(from)
    console.log(next)
    //获取token
    const token = ustore.getToken;
    if(token){
         //是否是在登录和首页来的
        if(to.path === '/login' || to.path === '/'){
              next({path:'/'})
        }else{
            //判断权限
            const hasRoles = ustore.getCodeList.length > 0
            if(hasRoles){
                console.log('当前路由列表:', router.getRoutes())
                next()
            }else{
            try{
                //获取用户信息
                await ustore.getInfo()
                //获取菜单数据
                await mstore.getMenuList(router,ustore.getUserId)
                console.log('当前路由列表:', router.getRoutes())
                //等待路由挂载
                 next({...to,replace:true})
            }catch(error){
                //清空数据
                sessionStorage.clear()
                next({path:'/login'})
            }
        }
        }
    }else{
        if(whiteList.indexOf(to.path) !== -1){
             next()
        }else{//不在白名单，跳转登录
             next({path:'/login'})
        }
    } 
})